//
//  Copyright (C) 2011 Ray Wang(fangshi168775@hotmail.com).  All Rights Reserved.
//
//  This is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This software is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this software; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
//  USA.
//
package ray.pcvnccontroler;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;

public class PCVNCControler extends Activity {
	private RfbProto rfb;
	private EditText addressText;
	private EditText portText;
	private EditText passwordText;
	private CheckBox rememberPwdChk;
	private Button   conButton;
	private SharedPreferences prefs;
	private static final String PREF_ADDRESS = "PREF_ADDRESS";
	private static final String PREF_PORT = "PREF_PORT";
	private static final String PREF_PASSWORD = "PREF_PASSWORD";
	private static final String PREF_REMEMBER_PASSWD = "PREF_REMEMBER_PASSWD";
	
	private void SetSavedParams()
	{
		String value;
		boolean checked;
		
		value = prefs.getString(PREF_ADDRESS,"");
		addressText.setText(value.toCharArray(), 0, value.length());
		
		value = prefs.getString(PREF_PORT,"5900");
		portText.setText(value.toCharArray(), 0, value.length());
		
		value = prefs.getString(PREF_PASSWORD,"");
		passwordText.setText(value.toCharArray(), 0, value.length());
	
		checked = prefs.getBoolean(PREF_REMEMBER_PASSWD, true);
		rememberPwdChk.setChecked(checked);	
	}
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        addressText = (EditText) findViewById(R.id.txt_address);
		portText = (EditText) findViewById(R.id.txt_port);
		passwordText = (EditText) findViewById(R.id.txt_password);
		conButton = (Button) findViewById(R.id.btn_connect);
		rememberPwdChk = (CheckBox)findViewById(R.id.chk_save_password);
		rfb = new RfbProto();
		conButton.setOnClickListener(new View.OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				try
				{
					//connectVnc();
					SaveParams();
					showDialog(R.layout.shortcut);
				}
				catch (Exception e)
				{
					Context context = getApplicationContext();
					int duration = Toast.LENGTH_SHORT;
					Toast toast = Toast.makeText(context, R.string.con_error, duration);
					toast.show();
				}
			}
		});
		
		Context context = getApplicationContext();
		prefs = PreferenceManager.getDefaultSharedPreferences(context);
		SetSavedParams();
    }
    
    
    private void SaveParams()
    {
    	Editor editor = prefs.edit();
    	boolean checked;
    	editor.putString(PREF_ADDRESS, addressText.getText().toString());
    	editor.putString(PREF_PORT, portText.getText().toString());
    	checked = rememberPwdChk.isChecked();
    	if(checked)
    	{
    		editor.putString(PREF_PASSWORD, passwordText.getText().toString());
    	}
    	else
    	{
    		editor.putString(PREF_PASSWORD, "");
    	}
    	editor.putBoolean(PREF_REMEMBER_PASSWD, checked);
    	editor.commit();
    }
    
    private void connectVnc () throws Exception
    {
    	int port = Integer.parseInt((portText.getText().toString()));
    	if(rfb.closed() == false)
    	{
    		rfb.close();
    	}
    	rfb.connect(addressText.getText().toString(), port);
    	
    	rfb.readVersionMsg();
    	rfb.writeVersionMsg();
    	
    	int secType = rfb.negotiateSecurity();
		int authType;
		if (secType == RfbProto.SecTypeTight) {
			rfb.initCapabilities();
			rfb.setupTunneling();
			authType = rfb.negotiateAuthenticationTight();
		} else {
			authType = secType;
		}

		switch (authType) {
		case RfbProto.AuthNone:
			rfb.authenticateNone();
			break;
		case RfbProto.AuthVNC:
			rfb.authenticateVNC(passwordText.getText().toString());
			break;
		default:
			throw new Exception("Unknown authentication scheme " + authType);
		}
		
		rfb.writeClientInit();
		rfb.readServerInit();
    }
    
    protected Dialog onCreateDialog(int id) 
    {
    	switch(id)
    	{
    	case R.layout.shortcut:
    		return new ShortCutDialog(this, rfb);
    	case R.layout.input:
    		return new InputDialog(this, rfb);
    	case R.layout.mouse:
    		return new MouseDialog(this, rfb);
    	}
		return null;
	}
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
        if(rfb.closed() == false)
        {
        	rfb.close();
        }
    }

}